var express=require("express");
var router=express.Router();
var pool=require("../pool");
var query=require("./query");


// 获取购物车数据
router.get("/",(req,res)=>{
    var {uid} =req.query;
  var sql=`select cid,pid,maxpic,pname,price,count from at_cart inner join at_product on pid=cpid where cuid=?`;
  pool.query(sql,[uid],(err,result)=>{
    res.send(result);
  })
// console.log("ok")
})


// 详情页进行购物车添加
router.get("/add",(req,res)=>{
  var {pid,count,uid}=req.query;

  var sql="select * from at_cart where cuid=? and cpid=?";
  query(sql,[uid,pid])
  .then(result=>{
    if(result.length==0){
      var sql="insert into at_cart values(null,?,?,?)";
      pool.query(sql,[uid,pid,count],(err,result)=>{
        res.send({msg:"加入购物车成功"});
      })
    }else{
      var sql="update at_cart set count=count+? where cuid=? and cpid=?";
      pool.query(sql,[count,uid,pid],(err,result)=>{
        res.send({msg:"加入购物车成功"});
      })
    }
  })
})





// 购物车页进行数据的更新与删除
router.get("/update",(req,res)=>{
  var {cid,count}=req.query;
  if(count>0){
    var sql="update at_cart set count=? where cid=?";
    pool.query(sql,[count,cid],(err,result)=>{
      res.send({msg:`更新成功`});
    })
  }else{
    var sql="delete from at_cart where cid=?";
    pool.query(sql,[cid],(err,result)=>{
      res.send({msg:`删除成功`});
    })
  }
})

module.exports = router;